package com.fast.alden.common.service.impl;


import com.fast.alden.common.exception.BizException;
import com.fast.alden.common.exception.BizExceptionEnum;
import com.fast.alden.common.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * 本地文件服务
 */
@Service
public class LocalFileServiceImpl implements FileService {
    @Value("${fast-alden.file.local.upload-path}")
    private String uploadPath;
    @Value("${fast-alden.file.local.upload-access-prefix}")
    private String uploadAccessPrefix;

    @Override
    public String upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BizException(BizExceptionEnum.FILE_IS_EMPTY);
        }

        String relPath = this.buildFilePath(file);
        File destDir = new File(uploadPath);
        File dest = new File(destDir.getCanonicalPath() + "/" + relPath);
        File destParent = dest.getParentFile();
        if (!destParent.exists()) {
            destParent.mkdirs();
        }
        dest.createNewFile();
        file.transferTo(dest);

        String url = uploadAccessPrefix + relPath;
        return url;
    }

    private String buildFilePath(MultipartFile file) {
        long timestamp = Calendar.getInstance().getTimeInMillis();
        return timestamp + "_" + file.getOriginalFilename();
    }
}
